package com.flyduck.modules.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyduck.common.exception.BusinessException;
import com.flyduck.modules.app.constant.AppConstant;
import com.flyduck.entity.AppUser;
import com.flyduck.mapper.AppUserMapper;
import com.flyduck.modules.app.service.AppLoginService;
import com.flyduck.modules.app.vo.login.AppCaptchaRespVO;
import com.flyduck.modules.app.vo.login.AppLoginReqVO;
import com.flyduck.modules.app.vo.login.AppLoginRespVO;
import com.flyduck.modules.app.vo.login.AppRegisterReqVO;
import com.flyduck.utils.BeanUtils;
import com.flyduck.utils.JwtUtils;
import com.flyduck.utils.RedisUtils;
import com.google.code.kaptcha.Producer;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * LoginServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024/5/9
 */
@Service
public class AppLoginServiceImpl implements AppLoginService {

    @Resource
    private AppUserMapper appUserMapper;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private Producer producer;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public AppLoginRespVO login(AppLoginReqVO appLoginReqVO) {
        //校验用户名密码
        List<AppUser> appUserList = appUserMapper.selectList(
                new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getUsername, appLoginReqVO.getUsername())
        );
        if(CollectionUtil.isEmpty(appUserList)){
            throw new BusinessException("用户不存在");
        }
        AppUser appUser = appUserList.get(0);
        if (!appUser.getPassword().equals(SecureUtil.md5(appLoginReqVO.getPassword()))) {
            throw new BusinessException("密码错误");
        }

        //更新最后登录时间
        appUser.setLastLogin(LocalDateTime.now());
        appUserMapper.updateById(appUser);

        //生成token
        String token = jwtUtils.generateToken(appUser.getId(),"APP");

        AppLoginRespVO.AppUserVO appUserVO = BeanUtils.toBean(appUser, AppLoginRespVO.AppUserVO.class);
        AppLoginRespVO appLoginRespVO = new AppLoginRespVO();
        appLoginRespVO.setToken(token);
        appLoginRespVO.setUserInfo(appUserVO);
        return appLoginRespVO;
    }

    @Override
    public AppCaptchaRespVO getCaptcha() {
        //生成uuid和验证码
        String uuid = UUID.randomUUID().toString();
        String code = producer.createText();

        //生成base64编码的图片验证码
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        BASE64Encoder encoder = new BASE64Encoder();
        String base64Img = "data:image/jpeg;base64," + encoder.encode(outputStream.toByteArray());

        //把uuid和验证码存储到redis
        redisUtils.set(AppConstant.RedisKeyConstant.APP_CAPTCHA_PREFIX + uuid, code,120);


        //返回uuid和base64图片
        AppCaptchaRespVO appCaptchaRespVO = new AppCaptchaRespVO();
        appCaptchaRespVO.setUuid(uuid);
        appCaptchaRespVO.setBase64Img(base64Img);
        return appCaptchaRespVO;
    }

    @Override
    public void register(AppRegisterReqVO appRegisterReqVO) {
        //验证验证码是否正确
        Object redisCode = redisUtils.get(AppConstant.RedisKeyConstant.APP_CAPTCHA_PREFIX + appRegisterReqVO.getUuid());
        if(!appRegisterReqVO.getCode().equals(redisCode)){
            throw new BusinessException("验证码错误");
        }

        //判断用户名是否已经存在
        Long count = appUserMapper.selectCount(
                new LambdaQueryWrapper<AppUser>()
                        .eq(AppUser::getUsername, appRegisterReqVO.getUsername())
        );
        if (count > 0) {
            throw new BusinessException("用户不存在");
        }

        //注册用户
        AppUser appUser = new AppUser();
        appUser.setUsername(appRegisterReqVO.getUsername());
        appUser.setPassword(SecureUtil.md5(appRegisterReqVO.getPassword()));
        appUser.setCreated(LocalDateTime.now());
        appUserMapper.insert(appUser);
    }
}
